<?php
/**
 * this Dig_Navigation_Writer class writes a Zend_Navigation object
 * to an XML file with Zend_Config_Writer_Xml
 * 
 */
class Dig_Navigation_Writer
{
    /**
     * the navigation object
     *
     * @var Zend_Navigation
     */
    protected $_navigation;
    /**
     * the full path to the XML source file
     *
     * @var string
     */
    protected $_filename;
    /**
     * the config section, defaults to 'default'
     *
     * @var string
     */
    protected $_section;
    /**
     * you pass the Dig_Navigation_Writer a Zend_Navigation object
     * the filename of the XML file to write it to
     * and optionally the config section. Using config sections
     * enables you to manage multiple sites with one tree
     *
     * @param Zend_Navigation $navigation
     * @param string $filename
     * @param string $section
     */
    public function __construct (Zend_Navigation $navigation, $filename, $section = 'default')
    {
        $this->_navigation = $navigation;
        $this->_filename = $filename;
        $this->_section = $section;
    }
    /**
     * the load method sanitizes the navigation object
     * and builds it into a clean array which the config writer will 
     * then use to build the config object
     *
     * @param array $pages
     * @param array $config
     * @return array
     */
    protected function _load ($pages, $config = array())
    {
        if (is_array($pages) && count($pages) > 0) {
            foreach ($pages as $page) {
                $id = $page->getId();
                $pageArray = $page->toArray();
                if (is_array($pageArray['pages']) && count($pageArray['pages']) > 0) {
                    $config[$id]['pages'] = $this->_load($page->getPages());
                }
                unset($pageArray['pages']);
                foreach ($pageArray as $key => $value) {
                    if (! empty($value)) {
                        $config[$id][$key] = $value;
                    }
                }
            }
        }
        return $config;
    }
    /**
     * the write method builds the config object from the Zend_Navigation object
     * then writes it to the file
     *
     * @return bool
     */
    public function write ()
    {
        $config = new Zend_Config_Xml($this->_filename, null);
        $configArray = $config->toArray();
        $configArray[$this->_section] = $this->_load($this->_navigation->getPages());
        $writer = new Zend_Config_Writer_Xml(array('config' => new Zend_Config($configArray) , 'filename' => $this->_filename));
        return $writer->write();
    }
}
?>